/**
 * 
 */
package ro.dta.idbi.ui.patterns;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JLabel;

import ro.dta.idbi.interfaces.sql.ISqlColumn;
import ro.dta.idbi.interfaces.sql.ISqlConstruct;
import ro.dta.idbi.interfaces.sql.ISqlTable;
import ro.dta.idbi.interfaces.ui.IMainFrame;
import ro.dta.idbi.patterns.AddIntersection;
import ro.dta.idbi.ui.sql.SqlForeignKeyCell;
import ro.dta.idbi.ui.sql.SqlGraph;
import ro.dta.idbi.ui.sql.SqlTableCell;
import uk.ac.ic.doc.automed.reps.Schema;

import com.mxgraph.layout.hierarchical.mxHierarchicalLayout;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxEvent;
import com.mxgraph.util.mxEventObject;
import com.mxgraph.util.mxEventSource.mxIEventListener;

/**
 * UI for the addition of intersection transformation pattern
 * 
 * @author Tudor Dobrila
 * 
 */
public class AddIntersectionDialog extends AbstractPatternDialog {

	private static final long serialVersionUID = 1440805736712900975L;
	private final static Logger LOGGER = Logger
			.getLogger("ro.dta.idbi.ui.patterns.AddIntersectionDialog");

	/**
	 * Check if the current pattern can be applied over a given set of objects
	 * 
	 * Used to check if the items selected by the user in the UI can be used to
	 * apply this transformation pattern over them
	 * 
	 * @param schema
	 *            Schema in the context of which to check the validity of the
	 *            array of objects
	 * @param objects
	 *            Set of objects
	 * @return True if pattern can be applied over set of objects, false
	 *         otherwise
	 */
	public static boolean isValid(final Schema schema, final Object[] objects) {
		if (objects.length < 2) {
			return false;
		}

		// All selected objects must be tables
		for (Object o : objects) {
			if (!(o instanceof ISqlTable)) {
				return false;
			}
		}

		// Add selected tables must have the same primary keys
		final ISqlTable fTbl = (ISqlTable) objects[0];
		final List<String> fpks = AddSubsetDialog.getPKNames(fTbl.getPrimaryKey());

		for (int i = 1; i < objects.length; i++) {
			final ISqlTable crtTbl = (ISqlTable) objects[i];
			final List<String> crtpks = AddSubsetDialog.getPKNames(crtTbl.getPrimaryKey());

			if (fpks.size() != crtpks.size()) {
				return false;
			}

			for (String pk : fpks) {
				if (!crtpks.contains(pk)) {
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * Addition of intersection pattern dialog class constructor
	 * 
	 * @param parentFrame
	 *            Parent frame of this dialog
	 * @param schema
	 *            Schema over which the transformation is applied
	 * @param element
	 *            Sql construct(s) over which the transformation is applied
	 * @param beforeLabel
	 *            Label for the before diagram
	 * @param afterLabel
	 *            Label for the transformed diagram
	 */
	public AddIntersectionDialog(final IMainFrame parentFrame, final Schema schema,
			final ISqlConstruct[] element, final JLabel beforeLabel, final JLabel afterLabel) {
		super(parentFrame, schema, element, beforeLabel, afterLabel);

		if (!isValid(schema, element)) {
			throw new IllegalArgumentException(
					"This pattern can't be applied to the given elements");
		}

		updateMacro("newTable");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ro.dta.idbi.ui.patterns.AbstractTransDialog#createOriginalDiagram()
	 */
	@Override
	protected mxGraphComponent createOriginalDiagram() {
		final SqlGraph graph = new SqlGraph();
		graph.getModel().beginUpdate();

		try {
			for (int i = 0; i < element.length; i++) {
				final SqlTableCell crtTbl = (SqlTableCell) element[i];
				final SqlTableCell newTable = (SqlTableCell) crtTbl.clone();
				final mxGeometry newGeometry = new mxGeometry(i * 170 + 5, 5, element[i]
						.getGeometry().getWidth(), element[i].getGeometry().getHeight());
				newTable.setGeometry(newGeometry);
				newTable.layout(graph);
			}
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			graph.setAutoSizeCells(true);
			graph.getModel().endUpdate();
		}

		return new mxGraphComponent(graph);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ro.dta.idbi.ui.patterns.AbstractTransDialog#createTransformedDiagram()
	 */
	@Override
	protected mxGraphComponent createTransformedDiagram() {
		final SqlGraph graph = new EditableGraph();
		graph.getModel().beginUpdate();

		SqlTableCell intTbl = null;
		try {
			SqlTableCell[] newTables = new SqlTableCell[element.length];

			for (int i = 0; i < element.length; i++) {
				final SqlTableCell crtTbl = (SqlTableCell) element[i];
				newTables[i] = (SqlTableCell) crtTbl.clone();
				final mxGeometry newGeometry = new mxGeometry(i * 170 + 5, 5, element[i]
						.getGeometry().getWidth(), element[i].getGeometry().getHeight());
				newTables[i].setGeometry(newGeometry);
				newTables[i].layout(graph);
			}

			intTbl = new SqlTableCell(null, null, "", "newTable", new mxGeometry(), "SEL_TABLE");
			final List<ISqlColumn> pkCols = newTables[0].getPrimaryKey();
			for (ISqlColumn c : pkCols) {
				final ISqlColumn newCol = (ISqlColumn) c.clone();
				intTbl.addColumn(newCol);
			}			
			intTbl.relayout(graph);

			for (int i = 0; i < element.length; i++) {
				final SqlForeignKeyCell foreignKey = new SqlForeignKeyCell(null, null, "", "", intTbl,
						newTables[i], "FK_EDGE");
				graph.addCell(foreignKey, graph.getDefaultParent());
			}
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			final mxHierarchicalLayout layout = new mxHierarchicalLayout(graph);
			layout.execute(graph.getDefaultParent());
			graph.setAutoSizeCells(true);
			graph.getModel().endUpdate();
		}

		final mxGraphComponent gComp = new mxGraphComponent(graph);
		gComp.setEnterStopsCellEditing(true);
		gComp.addListener(mxEvent.LABEL_CHANGED, new mxIEventListener() {

			@Override
			public void invoke(final Object arg0, final mxEventObject arg1) {
				final SqlTableCell table = (SqlTableCell) arg1.getProperty("cell");
				updateMacro(table.getValue().toString());
			}
		});

		if (intTbl != null) {
			gComp.startEditingAtCell(intTbl);
		}

		return gComp;
	}

	/**
	 * Update the macro command
	 * 
	 * @param newTableStr
	 *            Name of the intersection table
	 */
	private void updateMacro(final String newTableStr) {
		final StringBuilder macro = new StringBuilder(AddIntersection.COMMAND);
		macro.append(" (<<").append(newTableStr).append(">>, ");
		for (ISqlConstruct c : element) {
			macro.append("<<").append(c.getValue()).append(">>, ");
		}
		macro.setLength(macro.length() - 2);
		macro.append(")");
		macroField.setText(macro.toString());
	}

}
